package com.example.springblog.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

public class SecurityUtils {
    /*
    * 用户注册时加密
    * */
    public static String encrypt(String password){
        //生成随机盐值
        String salt= UUID.randomUUID().toString().replace("-","");
        //对明文＋盐值进行MD5加密
        String finalPassword=DigestUtils.md5DigestAsHex((password+salt).getBytes());
        return salt+finalPassword;
    }

    /*
    * 验证密码是否正确
    * */
    public static boolean verify(String inputPassword,String sqlPassword) {
        if (!StringUtils.hasLength(inputPassword)){
            return false;
        }
        if (sqlPassword==null || sqlPassword.length() !=64){
            return false;
        }
        String salt=sqlPassword.substring(0,32);
        System.out.println(salt);
        String finalPassword=DigestUtils.md5DigestAsHex((inputPassword+salt).getBytes());
        return (salt+finalPassword).equals(sqlPassword);
    }

}
